package org.iryshka.logit;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ConsoleFileLogging {

	public enum WritingTo{
		FILE,
		CONSOLE,
		FILE_CONSOLE,
		OFF
	}
	
	public static WritingTo destToWrite;
	
	private static File fileForLogging;
	private static FileOutputStream outstream;
	private static PrintStream printingStream;
	private static SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss.S");
	
	private static void logItToFile(String stringToLog){
		printingStream.println("<" + Thread.currentThread().getName() + "> " + "<" + dateFormat.format(new Date()) + ">: " + "<" + stringToLog + "> \n");
	}
	
	private static void logItToConsole(String stringToLog){
		System.out.println("<" + Thread.currentThread().getName() + "> " + "<" + dateFormat.format(new Date()) + ">: " + "<" + stringToLog + "> \n");
	}
	
	public static void whereToWrite(WritingTo destToWrite){
		ConsoleFileLogging.destToWrite = destToWrite;
	}
	
	public static void setDirToWrite(String dirToWrite){
		ConsoleFileLogging.fileForLogging = new File(dirToWrite);
		try (FileWriter outDelStream = new FileWriter (fileForLogging)){
			outDelStream.write("");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static void logIt (String stringToLog){
		try {
			if (fileForLogging != null){
				outstream = new FileOutputStream (fileForLogging, true);
				printingStream = new PrintStream(outstream);
			}
			if(destToWrite == WritingTo.FILE){
				logItToFile(stringToLog);
			}
			else if(destToWrite == WritingTo.CONSOLE){
				logItToConsole(stringToLog);
			}
			else if(destToWrite == WritingTo.FILE_CONSOLE){
				logItToFile(stringToLog);
				logItToConsole(stringToLog);
			}
			else{
				Thread.sleep(0);
			}
			
			if (fileForLogging != null){
				printingStream.close();
			}
			
		} catch (FileNotFoundException e) {
			System.out.println("FileNotFoundException occurs in logIt function!");
			e.printStackTrace();
		} catch (InterruptedException e) {
			System.out.println("InterruptedException occurs in logIt function!");
			e.printStackTrace();
		}
	}
}
